package com.bitrate.dagger.gateway.xss;

import java.beans.PropertyEditorSupport;

import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;

import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;

@ControllerAdvice
@RequiredArgsConstructor
public class FormXssClean {

	private final XssCleaner xssCleaner;

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		// 处理前端传来的表单字符串
		binder.registerCustomEditor(String.class, new StringPropertiesEditor(xssCleaner));
	}

	@RequiredArgsConstructor
	public static class StringPropertiesEditor extends PropertyEditorSupport {

		private final XssCleaner xssCleaner;

		@Override
		public String getAsText() {
			Object value = getValue();
			return value != null ? value.toString() : "";
		}

		@Override
		public void setAsText(String text) throws IllegalArgumentException {
			setValue(StrUtil.isNotEmpty(text) ? xssCleaner.clean(text) : null);
		}
	}

}
